﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using LinqToBing.Bing.Wrapper.Interfaces;
using LinqToBing.Bing.Wrapper.Results;
using LinqToBing.Bing.Wrapper.Search;

namespace LinqToBing.Bing.Wrapper.ExtensionMethods
{
    /// <summary>
    /// Extension methods for XDocument class.
    /// </summary>
    public static class XDocumentExt
    {
        /// <summary>
        /// Convert XDocument to List of List<ILiveSearchResultBase>
        /// </summary>
        /// <param name="xdoc">XDocument to convert.</param>
        /// <returns>Converted list.</returns>
        public static List<ISearchResult> ToList(this XDocument xdoc)
        {
            List<ISearchResult> Result = new List<ISearchResult>();
            if (xdoc.Root.Name.Equals("web:Web"))
            {
                int Total = xdoc.Root.GetInt32FromElement("web:Total");
                int Offset = xdoc.Root.GetInt32FromElement("web:Offset");
                XElement xelResults = xdoc.Root.Element("web:Results");
                xelResults.Elements("web:WebResult").ToList<XElement>().ForEach(elem =>
                    {
                        Result.Add(
                            new SearchResultWeb()
                            {
                                Title = elem.GetStringFromElement("web:Title"),
                                Description = elem.GetStringFromElement("web:Description"),
                                Url = elem.GetUriFromElement("web:Url")
                            }
                        );
                    });
            }
            return Result;
        }

    }
}
